package com.example.demo;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;

import javafx.scene.control.Pagination;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.util.List;
public class HelloApplication extends Application {
    private final int ROWS_PER_PAGE = 10; // 每页显示的行数
    private TableView<Person> tableView = new TableView<>();
    private Pagination pagination;
    private ObservableList<Person> data; // 保存数据

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        // 创建数据
        data = getInitialData();

        // 配置TableView
        setupTableView();

        // 创建分页控件
        pagination = new Pagination((data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE);
        pagination.setPageFactory(this::createPage);

        VBox vbox = new VBox(tableView, pagination);
        Scene scene = new Scene(vbox);

        primaryStage.setScene(scene);
        primaryStage.setTitle("可翻页表格示例");
        primaryStage.show();
    }

    private ObservableList<Person> getInitialData() {
        ObservableList<Person> data = FXCollections.observableArrayList();
        for (int i = 1; i <= 100; i++) {
            data.add(new Person("Name " + i, "Email " + i + "@example.com"));
        }
        return data;
    }

    private void setupTableView() {
        TableColumn<Person, String> nameColumn = new TableColumn<>("Name");
        nameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Person, String> emailColumn = new TableColumn<>("Email");
        emailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));

        tableView.getColumns().addAll(nameColumn, emailColumn);
    }

    private VBox createPage(int pageIndex) {
        int fromIndex = pageIndex * ROWS_PER_PAGE;
        int toIndex = Math.min(fromIndex + ROWS_PER_PAGE, data.size());

        List<Person> pageItems = data.subList(fromIndex, toIndex);
        ObservableList<Person> pageData = FXCollections.observableArrayList(pageItems);
        tableView.setItems(pageData);

        return new VBox(tableView);
    }

    public static class Person {
        private String name;
        private String email;

        public Person(String name, String email) {
            this.name = name;
            this.email = email;
        }

        public String getName() {
            return name;
        }

        public String getEmail() {
            return email;
        }
    }
}
